#[derive(Debug)]
enum CustomError {
    NotFound
}

// 自定义错误
impl std::fmt::Display for CustomError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

fn divide(x: i32, y: i32) -> Result<i32, String> {
    if y == 0 {
        Err("除数不能为零".to_string())
    } else {
        Ok(x / y)
    }
}

fn safe_divide(x: i32, y: i32) -> Result<i32, String> {
    let result = divide(x, y)?;  // `?` 简化错误传播
    Ok(result)
}

fn find_index(list: Vec<i32>, target: i32) -> Option<usize> {
    for (index, &item) in list.iter().enumerate() {
        if item == target {
            return Some(index);
        }
    }
    None
}

fn find_index_custom(list: Vec<i32>, target: i32) -> Result<i32, CustomError> {
    for &item in list.iter() {
        if item == target {
            return Ok(item);
        }
    }
    Err(CustomError::NotFound)
}

fn main() {

    let result = divide(10, 0);
    match result {
        Ok(value) => println!("计算结果: {}", value),
        Err(e) => println!("错误: {}", e),
    }

    let result = safe_divide(10, 2).unwrap();
    println!("计算结果: {}", result);

    let list = vec![10, 20, 30, 40, 50];

    let pos1 = find_index(list.clone(), 30);
    match pos1 {
        Some(index) => println!("元素位置: {}", index),
        None => println!("元素未找到"),
    }

    let pos2 = find_index(list, -1);
    match pos2 {
        Some(index) => println!("元素位置: {}", index),
        None => println!("元素未找到"),
    }

    let list2 = vec![10, 20, 30, 40, 50];
    let result1 = find_index_custom(list2.clone(), 20).unwrap();
    println!("元素: {}", result1);

    let result2 = find_index_custom(list2, -1).unwrap();
    println!("元素: {}", result2);
}

